#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include "log.hpp"

enum{
    SOCKET_ERR=1,
    BIND_ERR
};

Log lg;
uint16_t defaultport = 8080;
std::string defaultip = "0.0.0.0";
const int size = 1024;

typedef std::function<std::string(const std::string&)> func_t;

class UdpServer
{
public:
    UdpServer(const uint16_t& port = defaultport, const std::string ip = defaultip)
    : sockfd_(0), ip_(ip), port_(port), isrunning_(false)
    {}

    void Init()
    {
        // 1.创建udp socket
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if(sockfd_ < 0)
        {
            lg(Fatal, "socket create error, sockfd : %d", sockfd_);
            exit(SOCKET_ERR);
        }
        lg(Info, "socket create success, sockfd : %d", sockfd_);
        // 2.bind socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_); // 保证端口号为网络字节序，因为当前端口号是给对方发送的
        local.sin_addr.s_addr = inet_addr(ip_.c_str()); // string->uint32_t 、uint32_t必须是网络序列的

        if(bind(sockfd_,(const struct sockaddr*)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, errno : %d, err string : %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success, errno : %d, err string : %s", errno, strerror(errno));
    }

    void CheckUser(struct sockaddr_in client, const std::string& clientip, const uint16_t clientport)
    {
        auto iter = online_users_.find(clientip);
        if(iter == online_users_.end())
        {
            std::cout << "User :[" << clientip << ':' << clientport << "] add to online." << std::endl;
            online_users_[clientip] = client;
        }
    }

    void Broadcast(const std::string& info, const std::string& clientip, const uint16_t clientport)
    {
        for(auto& user : online_users_)
        {
            std::string message = "[";
            message += clientip;
            message += ':';
            message += std::to_string(clientport);
            message += "]# ";
            message += info;
            socklen_t len = sizeof(user.second);
            sendto(sockfd_, message.c_str(), message.size(), 0, (struct sockaddr*)(&user.second), len);
        }
    }

    void Run()
    {
        isrunning_ = true;
        char inbuffer[size];
        while(isrunning_)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_, inbuffer, sizeof(inbuffer)-1, 0, (struct sockaddr*)&client, &len);
            if(n < 0)
            {
                lg(Warning, "recvfrom error, errno : %d, err string : %s", errno, strerror(errno));
                continue;
            }

            std::string clientip = inet_ntoa(client.sin_addr);
            uint16_t clientport = ntohs(client.sin_port);
            CheckUser(client, clientip, clientport);

            std::string info = inbuffer;
            Broadcast(info, clientip, clientport);
        }
    }

    ~UdpServer()
    {
        if(sockfd_ > 0) close(sockfd_);        
    }
private:
    int sockfd_;
    std::string ip_;
    uint16_t port_;
    bool isrunning_;
    std::unordered_map<std::string, struct sockaddr_in> online_users_;
};

